<script setup lang="ts">

import { computed, reactive, watch } from "vue";
import { SessionAffinityConfigType } from "../../types/SessionAffinity"
import { SessionAffinityConfig } from "../../services/client";
import NtmSessionAffinityCookieConfigEditor from "./NtmSessionAffinityCookieConfigEditor.vue";
import ClusterConfigConstants from "../../constants/ClusterConfigConstants";

const model = defineModel<SessionAffinityConfigType>({ default: new SessionAffinityConfig() })
const props = defineProps<{ propNamePrefix?: string }>();

let modelValue = reactive(model.value);
watch(modelValue, (value) => {
    model.value = value;
}, { deep: true })

const computedPropName = (propName: string) => {
    return computed(() => {
        if (props.propNamePrefix) {
            return `${props.propNamePrefix}.${propName}}`
        }
        else {
            return propName;
        }
    })
}

const enabledPropName = computedPropName('enabled');
const policyPropName = computedPropName('policy')
const failurePolicyPropName = computedPropName('failurePolicy')
const affinityKeyNamePropName = computedPropName('affinityKeyName')
const cookiePropName = computedPropName('cookie');

</script>

<template>
    <ElFormItem label="Enabled" :prop="enabledPropName">
        <ElSwitch v-model="modelValue.enabled"></ElSwitch>
    </ElFormItem>
    <ElFormItem label="Affinity Key Name" :prop="affinityKeyNamePropName">
        <ElInput v-model="modelValue.affinityKeyName"></ElInput>
    </ElFormItem>
    <ElFormItem label="Policy" :prop="policyPropName">
        <ElSelect v-model="modelValue.policy" clearable>
            <ElOption v-for="(policy, index) in ClusterConfigConstants.SessionAffinity.Policies" :key="index"
                :value="policy">
                {{ policy }}
            </ElOption>
        </ElSelect>
    </ElFormItem>
    <ElFormItem label="Failure Policy" :prop="failurePolicyPropName">
        <ElSelect v-model="modelValue.failurePolicy" clearable>
            <ElOption v-for="(policy, index) in ClusterConfigConstants.SessionAffinity.FailurePolicies" :key="index"
                :value="policy">
                {{ policy }}
            </ElOption>
        </ElSelect>
    </ElFormItem>
    <ElFormItem label="Cookie" :prop="cookiePropName">
        <slot name="cookie" :cookie="modelValue.cookie">
            <NtmSessionAffinityCookieConfigEditor class="cookie-part" :prefix="cookiePropName" v-model="modelValue.cookie">
            </NtmSessionAffinityCookieConfigEditor>
        </slot>
    </ElFormItem>
</template>